package com.ddxcloud.movie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.SymmetricAlgorithm;
import com.alibaba.fastjson.JSONObject;
import com.ddxcloud.common.constants.enums.ItemColumnTypeEnum;
import com.ddxcloud.common.handler.BusinessException;
import com.ddxcloud.common.utils.*;
import com.ddxcloud.common.utils.config.SuihbConfig;
import com.ddxcloud.movie.data.dto.*;
import com.ddxcloud.movie.data.entity.*;
import com.ddxcloud.movie.mapper.UserMapper;
import com.ddxcloud.movie.service.ActivityService;
import com.ddxcloud.movie.service.SuihbService;
import com.ddxcloud.movie.service.UserService;
import com.ddxcloud.movie.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Slf4j
public class SuihbServiceImpl implements SuihbService {
    @Value("${spring.profiles.active}")
    private String active;

    @Resource
    UserMapper userMapper;

    @Resource
    UserService userService;

    @Resource
    ActivityService activityService;

    @Override
    public String login() {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String signTime = format.format(new Date());
        String signId = IdUtil.randomUUID();
        ThirdLoginDTO loginDto=new ThirdLoginDTO();
        String secret = Sm4Util.encryptSm4(SuihbConfig.SECRET);
        loginDto.setSecret(secret);
        loginDto.setClientId(SuihbConfig.CLIENT_ID);
        SignDTO signDto = generateSign(SuihbConfig.CLIENT_ID, signId, signTime);
        signDto.setBody(loginDto);
        String login = JSONObject.toJSONString(signDto);
        String url="";
        if (active.equals("prod")){
            url=SuihbConfig.API_ROOT_PROD+SuihbConfig.LOGIN_URL;
        }else{
            url=SuihbConfig.API_ROOT_TEST+SuihbConfig.LOGIN_URL;
        }
        String result = SkipHttpsUtil.doPostHttps(url, login, null);
        JSONObject jsonObject = JSONObject.parseObject(result);
        if (jsonObject.getInteger("code")!=0){
            throw new BusinessException(jsonObject.getString("msg"));
        }
        String data = jsonObject.getString("data");
        JSONObject jsonObject1 = JSONObject.parseObject(data);
        return jsonObject1.getString("accessToken");
    }

    @Override
    public String myBusiness(ParamDataDTO dto) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String signTime = format.format(new Date());
        //内部订单号
        String orderNo="SHB"+System.currentTimeMillis();
        //基本信息、附件
        List<ItemColumn> itemList = new ArrayList<>();
        //事项信息
        itemList.add(ItemColumn.builder().key("事项信息").show(1).sort(1)
                .type(ItemColumnTypeEnum.SUBFORM.getCode()).subItems(new ArrayList<ItemColumn>() {{
                    add(ItemColumn.builder().key("bizAcpNo").keyAlias("业务流水号").show(1).sort(0).
                            type(ItemColumnTypeEnum.STRING.getCode()).value(orderNo).build());
                    add(ItemColumn.builder().key("insuName").keyAlias("申请人姓名").show(1).sort(1).
                            type(ItemColumnTypeEnum.STRING.getCode()).valueAlias(DesensUtils.desensName(dto.getInsuName())).build());
                    add(ItemColumn.builder().key("insuIdCard").keyAlias("申请人证件号码").valueAlias(DesensUtils.desensIdCard(dto.getInsuIdCard()))
                            .type(ItemColumnTypeEnum.STRING.getCode()).show(1).sort(2).build());
                    add(ItemColumn.builder().key("conerTel").keyAlias("联系电话").valueAlias(DesensUtils.desensMobile(dto.getConerTel()))
                            .type(ItemColumnTypeEnum.STRING.getCode()).show(1).sort(3).build());
                    add(ItemColumn.builder().key("bankCardno").keyAlias("单位账户银行行号").valueAlias(DesensUtils.desensBankCard(dto.getBankCardno()))
                            .type(ItemColumnTypeEnum.STRING.getCode()).show(1).sort(12).build());
                    add(ItemColumn.builder().key("processingTime").keyAlias("办理时间").valueAlias(dto.getProcessingTime())
                            .type(ItemColumnTypeEnum.STRING.getCode()).show(1).sort(8).build());

                }}).build());
        //处理附件信息
        if (null != dto.getFiles() && dto.getFiles().size() > 0) {
            dealFiles(itemList, dto.getFiles());
        }
        //添加到我的办事
        ShbDTO formItem = ShbDTO.builder().matter(dto.getMatter())
                .itemCode("SHB0012310")
                .idCard(Sm4Util.encryptSm4(dto.getInsuIdCard()))
                .name(dto.getInsuName())
                .acceptTime(new Date())
                .isfr(dto.getIsfr())
                .tpYwls(orderNo)
                .status(0)
                .itemType(0)
                .itemColumns(itemList).build();
        SignDTO addobj = generateSign(SuihbConfig.CLIENT_ID, IdUtil.randomUUID(), signTime);
        addobj.setBody(formItem);
        String addJson = JSONObject.toJSONString(addobj);
        String accessToken = this.login();
        String addUrl = SuihbConfig.API_ROOT_TEST+SuihbConfig.MY_BUSINESS_URL;
        String s = SkipHttpsUtil.doPostHttps(addUrl, addJson, accessToken);
        JSONObject jsonObject = JSONObject.parseObject(s);
        if (jsonObject.getInteger("code")!=0){
            throw new BusinessException(jsonObject.getString("msg"));
        }
        return jsonObject.getString("data");
    }

    @Override
    public String callback(CallbackMsgDTO dto) {
        return null;
    }

    @Override
    public Map<String, Object> analysis(String sign) {
        log.info("加密数据：{}",sign);
        byte[] key = SecureUtil.generateKey(SymmetricAlgorithm.DES.getValue(), SuihbConfig.USER_INFO_SECRET.getBytes()).getEncoded();
        cn.hutool.crypto.symmetric.DES des = SecureUtil.des(key);
        byte[] decrypt = des.decrypt(sign);
//      String s = Sm4Util.decryptSm4(sign);
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] decode = decoder.decode(decrypt);
        String userInfo = new String(decode);
        log.info("穗好办用户信息解密：{}",userInfo);
        JSONObject jsonObject = JSONObject.parseObject(userInfo);
        String phone = jsonObject.getString("mobile");
        Integer isExist = userMapper.isExistUserByUsername(phone);
        User user = new User();
        if (isExist == null) {
            user.setUsername(phone);
            userMapper.insert(user);
            // activityService.getNewUserActivity(user);
        } else {
            user = userService.getUserByMobile(phone);
        }
        Map<String, Object> params = new HashMap<>();
        params.put("userId", user.getUserId());
        params.put("token", JwtUtil.createJWT(params));
        params.put("userInfo", user);
        params.put("exp", System.currentTimeMillis() + JwtUtil.timeMillis);
        return params;
    }

    public static SignDTO generateSign(String clientId, String signId, String signTime) {
        String signCode = SignUtil.getShbSign(clientId + signId + signTime);
        SignDTO signResult = new SignDTO();
        signResult.setSignCode(signCode);
        signResult.setSignId(signId);
        signResult.setSignTime(signTime);
        signResult.setSignCode(signCode);
        return signResult;
    }
    public static void dealFiles(List<ItemColumn> itemList, List<FileDTO> files) {
        itemList.add(
                ItemColumn.builder().key("上传资料").show(1).sort(3)
                        .type(ItemColumnTypeEnum.SUBFORM.getCode()).subItems(
                                new ArrayList<ItemColumn>() {{
                                    for (int i = 0; i < files.size(); i++) {
                                        int j = 1 + i;
                                        FileDTO dto = files.get(i);
                                        String fileUpload = "fileUpload" + j;

                                        Integer code = null;
                                        //类型
                                        if ("doc".equals(dto.getSuffix()) || "docx".equals(dto.getSuffix())) {
                                            code = ItemColumnTypeEnum.WORD_DOC_URL.getCode();
                                        } else if ("xls".equals(dto.getSuffix()) || "xlsx".equals(dto.getSuffix())) {
                                            code = ItemColumnTypeEnum.EXCEL_URL.getCode();
                                        } else if ("ppt".equals(dto.getSuffix())) {
                                            code = ItemColumnTypeEnum.PPT_URL.getCode();
                                        } else if ("pdf".equals(dto.getSuffix())) {
                                            code = ItemColumnTypeEnum.PDF_URL.getCode();
                                        } else {
                                            code = ItemColumnTypeEnum.IMG_URL.getCode();
                                        }
                                        add(ItemColumn.builder().key(fileUpload).keyAlias(dto.getName()).show(1).sort(j)
                                                .type(code).valueAlias(dto.getFileId()).build());
                                    }
                                }}).build());
    }
}
